package com.browsesoft.util;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求工具类
 * 
 * @author Administrator
 * 
 */
public class RequestHelper {

	/**
	 * 用请求中的参数替换字符串中 #xxx#形式的同名参数
	 * 
	 * @return
	 */
	public static String replaceParameter(HttpServletRequest request, String str) {
		Map map = request.getParameterMap();
		return replaceParameter(str, map, true);
	}

	public static String replaceParameter(String str, Map map,
			boolean replaceWhite) {
		Iterator iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = (String) entry.getKey();
			Object obj = entry.getValue();
			String value = getValue(obj);
			// 如果有值，或者替换成空，则替换，否则不替换
			if ((value != null && !value.equals("")) || replaceWhite) {
				str = str.replaceAll("#" + key + "#", value);
			}
		}
		return str;
	}

	private static String getValue(Object obj) {
		if (obj instanceof String) {
			return (String) obj;
		} else if (obj instanceof String[]) {
			return ((String[]) obj)[0];
		} else {
			throw new RuntimeException("无法进行转换");
		}
	}

}
